package com.realshare.bby.service.integral;

import com.realshare.bby.model.LogWxorsinvalid;
import com.realshare.frame.component.quartz.base.AutoScheduler;
import com.realshare.frame.component.quartz.base.BaseScheduler;
import com.realshare.frame.util.DateUtils;
import com.realshare.frame.util.EasyHashMap;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.SQLReady;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 订单未兑换失效积分计算
 * author leisure
 * email 15075107120@139.com
 * create 2018-11-23 下午 5:54
 * modify 2018-11-23 下午 5:54
 **/
@Service
//自动注入定时任务，并指定任务名称
@AutoScheduler(name = "OrdersInvalidScheduler", group = "Integral")
//使用@DisallowConcurrentExecution设置不并发执行
@DisallowConcurrentExecution
public class OrdersInvalidScheduler extends BaseScheduler {

    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private SQLManager sqlManager;

    public OrdersInvalidScheduler() {
        super(true);
    }

    @Override
    public String setDescription() {
        return "订单未兑换失效积分计算";
    }

    @Override
    protected void executeInternal(JobExecutionContext context) {
        JobDetail jobDetail = context.getJobDetail();
        String workName = jobDetail.getKey().toString();
        log.info("开始订单未兑换失效积分返回作业，作业名称为：" + workName);
        doExecute();
        log.info("结束订单未兑换失效处理作业");
    }

    private void doExecute() {
        LogWxorsinvalid wxLog = new LogWxorsinvalid();
        wxLog.setId(UUID.randomUUID().toString());
        wxLog.setBeTime(DateUtils.getNowDateTime());
        String mess = "执行成功";
        business();
        wxLog.setMessage(mess);
        wxLog.setEnTime(DateUtils.getNowDateTime());
        sqlManager.insert(wxLog);
    }

    private void business() {
        log.info("开始处理订单未兑换失效返还积分");
        String sql = "select t.*,cm.ID cid from CONVERSION_ORDERS t " +
                "LEFT JOIN customer_means cm on cm.id = t.CUSTOMER_ID " +
                "where t.STATE='0' and t.CONVERLIMET_TIME<'" + DateUtils.formatLongDate(new Date()) + "'";
        // 1、查询需要处理的超时未兑换的订单
        log.info("查询需要处理的超时未兑换的订单" );
        List<EasyHashMap> mapList = sqlManager.execute(new SQLReady(sql), EasyHashMap.class);
        String now = DateUtils.formatLongDate(new Date());
        String upSql;
        for (EasyHashMap map : mapList) {
            String id = map.getString("ID");
            String cid = map.getString("CID");
            String productId = map.getString("PRODUCT_ID");
            String productCount = map.getString("SUM");
            String boId = map.getString("BO_ID");
            double integral = map.getDouble("INTEGRAL");
            // 2、返还用户积分
            upSql = "UPDATE customer_means SET INTEGRAL =INTEGRAL+" + integral + " WHERE ID='" + cid + "'";
            sqlManager.executeUpdate(new SQLReady(upSql));
            // 3、返还网点商品
            upSql = "UPDATE bo_distributed SET PRE_COUNT=PRE_COUNT-" + productCount +
                    " WHERE BO_ID='" + boId + "' and PRODUCT_ID='" + productId +
                    "' and PRE_COUNT>=" + productCount + " limit 1";
            sqlManager.executeUpdate(new SQLReady(upSql));
            // 4、更新订单状态
            upSql = "UPDATE CONVERSION_ORDERS SET STATE =3 WHERE ID='" + id + "'";
            sqlManager.executeUpdate(new SQLReady(upSql));
            // 5、插入增加返还积分日志
            upSql = "insert into INTEGRAL_LOG(id,quantity,unit,order_id,`DESCRIBE`,creator,create_time,`status`,identity_code) " +
                    " select '" + UUID.randomUUID() + "','" + integral + "','分','" + id + "','微信订单未兑换超时返还积分','system','" +
                    now + "','3',IDENTITY_CODE from customer_means where ID='" + cid + "'";
            sqlManager.executeUpdate(new SQLReady(upSql));
            // 6、插入增加返还积分流水
            upSql = "insert into integral_flow(id,type,title,quantity,deal_type,is_read,creator,create_time,`status`,data_time,ORG_CODE,clear_status,identity_code) " +
                    " select '" + UUID.randomUUID() + "','2','微信订单未兑换超时返还积分','" + integral +
                    "','1','0','system','" + now + "','1','" + now + "','" + boId + "','0',IDENTITY_CODE from customer_means where ID='" + cid + "'";
            log.info("插入增加返还积分流水" );
            sqlManager.executeUpdate(new SQLReady(upSql));
        }
        log.info("结束处理订单未兑换失效返还积分");
    }

}